<template>
  <div ref="catalog-container" v-show="display" class="doc-catalog-container">
    <div ref="catalog-list" class="doc-catalog-list">
      <el-tree
        :data="docCatalog"
        default-expand-all
        :expand-on-click-node="false"
        @node-click="goAnchor"
      />
<!--      <div-->
<!--        v-for="item in docCatalog"-->
<!--        :key="item.index"-->
<!--        class="line1 pointer hover-as-primary-btn m-b-8"-->
<!--        :style="initItemStyle(item)"-->
<!--        @click="goAnchor(item)"-->
<!--      >-->
<!--        {{ item.textContent }}-->
<!--      </div>-->
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  name: 'doc-catalog',
  props: {
    display: Boolean,
  },
  computed: {
    ...mapGetters(['docCatalog']),
  },
  mounted() {
    window.addEventListener('scroll', this.watchListTop);
  },
  destroyed() {
    window.removeEventListener('scroll', this.watchListTop);
  },
  methods: {
    // 目录的左缩进
    initItemStyle(item) {
      return `padding-left: ${item.headerIndex - 1}rem;`;
    },
    // 点击前往目录位置
    goAnchor({ contentAnchor }) {
      function doScroll(el, tiny) {
        let obj = el;
        let t = obj.offsetTop;
        while (obj.offsetParent) {
          obj = obj.offsetParent;
          t += obj.offsetTop;
        }
        document.documentElement.scrollTop = t - (tiny ? -200 : 65);
      }
      const el = document.querySelector(`[data-doc-catalog-index=${contentAnchor}]`);
      if (el) doScroll(el);
      else {
        const editor = document.querySelector('.doc-show-editor.tinymce-editor iframe');
        const eDocument = editor.contentWindow.document;
        const eEl = eDocument.querySelector(`[data-doc-catalog-index=${contentAnchor}]`);
        if (eEl) doScroll(eEl, true);
        else console.warn('未找到目录位置');
      }
    },
    // 监听当前目录的位置
    watchListTop() {
      const [container, list] = [this.$refs['catalog-container'], this.$refs['catalog-list']];
      const containerHeight = container.offsetHeight;
      const listHeight = list.offsetHeight;
      const top = container.getBoundingClientRect().top - 60; // container 顶部相对于显示区域顶部的距离
      // list 高度和 container 顶部padding高度 相加大于 container高度时，固定
      if (top < 0 && listHeight + Math.abs(top) < containerHeight) {
        list.style.top = `${Math.abs(top)}px`;
      } else if (top > 0) {
        list.style.top = '0';
      }
    },
  },
};
</script>

<style lang="scss">
.doc-catalog-container {
  position: relative;

  .doc-catalog-list {
    position: absolute;
    top: 0;
    width: 100%;
    max-height: 80vh;
    overflow-y: auto;
    margin-top: 1em;
    margin-bottom: 1em;
  }

  .el-tree-node__content {
    height: unset;
  }
  .el-tree-node__content>.el-tree-node__expand-icon {
    padding: 4px;
  }
  .el-tree-node__label {
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
</style>
